// common/db.js
const mysql = require('mysql2');
const config = require('../config');

const pool = mysql.createPool(config.db);

module.exports = {
    query: (sql, params, callback) => {
        pool.getConnection((err, conn) => {
            if (err) {
                callback(err, null);
            } else {
                conn.query(sql, params, (err1, results) => {
                    callback(err1, results);
                    conn.release();
                })
            }
        })
    },
    //sqlVsParams:数组，元素为 sql语句及参数组成的对象，如[{sql:'',params:[]}]
    dbTransaction: (sqlVsParams, callback) => {
        let results = [];
        pool.getConnection((err, conn) => {
            if (err) {
                conn.release();
                return callback(err, null);
            }
            conn.beginTransaction((err1) => {
                if (err1) {
                    conn.release();
                    return callback(err1, null);
                }
                sqlVsParams.forEach((item) => {
                    conn.query(item.sql, item.params, (err2, results1) => {
                        if (err2) {
                            conn.rollback(function(err3) {
                                conn.release();
                                return callback(err3, null);
                            });
                        } else {
                            results.push(results1);
                        }
                    })
                });
                conn.commit((err4) => {
                    if (err4) {
                        conn.release();
                        return callback(err4, null);
                    } else {
                        conn.release();
                        return callback(null, results);
                    }
                })
            })
        })
    }
}